﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using LiteDB;
using MyFound.UI.Forms;

namespace MyFound.UI
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = false;
            //dataGridView1.DataSource = new BindingList<DataGridRowModel>();
        }

        private int a = 0;
        private void Form1_Load(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem((state) =>
            {
                while (true)
                {
                    MyFound.Program.UpdateFoundEquity();
                    var data = GetData();

                    this.Invoke(new MethodInvoker(() =>
                    {
                        var selectedRows = dataGridView1.SelectedRows;
                        var indexList = new List<int>();
                        foreach (DataGridViewRow selectedRow in selectedRows)
                        {
                            indexList.Add(selectedRow.Index);
                        } 
                         
         
                        dataGridView1.DataSource = data;

                        //var bindingList = dataGridView1.DataSource as BindingList<DataGridRowModel>;

                        //var removeIds = bindingList.Where(x => data.Select(y => y.Id).Contains(x.Id)).ToList();
                        //removeIds.ToList().ForEach(d => bindingList.Remove(d));

                        //foreach (var d in data)
                        //{
                        //    var item = bindingList.FirstOrDefault(x => x.Id == d.Id);
                        //    if (item != null)
                        //    {
                        //        item.Code = d.Code;
                        //        item.Count = d.Count;
                        //        item.Equity = d.Equity;
                        //        item.GEquity = d.GEquity;
                        //        item.GProfit = d.GProfit;
                        //        item.GProfitRate = d.GProfitRate;
                        //        item.Principal = d.Principal;
                        //        item.Profit = d.Profit;
                        //        item.ProfitRate = d.ProfitRate;
                        //    }
                        //    else
                        //    {
                        //        item = new DataGridRowModel();
                        //        item.Id = d.Id;
                        //        item.Code = d.Code;
                        //        item.Count = d.Count;
                        //        item.Equity = d.Equity;
                        //        item.GEquity = d.GEquity;
                        //        item.GProfit = d.GProfit;
                        //        item.GProfitRate = d.GProfitRate;
                        //        item.Principal = d.Principal;
                        //        item.Profit = d.Profit;
                        //        item.ProfitRate = d.ProfitRate;
                        //        bindingList.Add(item);
                        //    }
                        //}


                        //foreach (var d in data)
                        //{
                        //    foreach (DataGridViewRow row in dataGridView1.Rows)
                        //    {
                        //        var drm = row.DataBoundItem as DataGridRowModel;
                        //        if (drm != null)
                        //        {
                        //            if (drm.Id == d.Id)
                        //            {
                        //                row.SetValues(drm.Code, drm.Count + (a++), drm.Equity, drm.Profit, drm.ProfitRate, drm.GProfit, drm.GProfitRate);
                        //                break;
                        //            }
                        //        }
                        //    }

                        //}

                        foreach (var i in indexList)
                        {
                            if (dataGridView1.RowCount > i)
                            {
                                dataGridView1.Rows[i].Selected = true;
                            }
                        }

                        for (var i = 0; i < dataGridView1.RowCount; i++)
                        {
                            var rate = dataGridView1.Rows[i].Cells["ProfitRate"].Value as decimal?;

                            if (rate.HasValue)
                            {
                                if (rate.Value > 0)
                                {
                                    dataGridView1.Rows[i].Cells["ProfitRate"].Style.ForeColor = Color.Red;
                                }
                                else if (rate.Value < 0)
                                {
                                    dataGridView1.Rows[i].Cells["ProfitRate"].Style.ForeColor = Color.Green;
                                }
                                else
                                {
                                    dataGridView1.Rows[i].Cells["ProfitRate"].Style.ForeColor = Color.Transparent;
                                }
                            }

                            var grate = dataGridView1.Rows[i].Cells["GProfitRate"].Value as decimal?;

                            if (grate.HasValue)
                            {
                                if (grate.Value > 0)
                                {
                                    dataGridView1.Rows[i].Cells["GProfitRate"].Style.ForeColor = Color.Red;
                                }
                                else if (grate.Value < 0)
                                {
                                    dataGridView1.Rows[i].Cells["GProfitRate"].Style.ForeColor = Color.Green;
                                }
                                else
                                {
                                    dataGridView1.Rows[i].Cells["GProfitRate"].Style.ForeColor = Color.Transparent;
                                }
                            }

                        }

                    }));
                    Thread.Sleep(5000);
                }
            });


        }

        IEnumerable<DataGridRowModel> GetData()
        {
            var rowModels = new List<DataGridRowModel>();
            var liteDatabase = new LiteDatabase("lite.db");
            var foundCol = liteDatabase.GetCollection<Found>("Found");
            var founds = foundCol.FindAll();
            var tradeCol = liteDatabase.GetCollection<Trade>("Trade");
            var trades = tradeCol.Find(x => x.RealCount > 0);

            founds.ToList().ForEach(found =>
            {
                found.GrEquity = FoundApi.GetGrEquity(found.Code);
                foundCol.Update(found);
            });

            //Console.Clear();
            trades.OrderBy(x => x.FdCode).ToList().ForEach(trade =>
            {
                DataGridRowModel model = new DataGridRowModel();
                rowModels.Add(model);
                var found = founds.First(f => f.Code == trade.FdCode);

                //Console.CursorVisible = false;

                var syl = (found.Equity - trade.RealEquity) / found.Equity;
                var gssyl = found.GrEquity > 0 ? (found.GrEquity - trade.RealEquity) / found.GrEquity : 0;

                model.GProfitRate = gssyl;
                model.ProfitRate = syl;
                model.Code = trade.FdCode;
                model.Count = trade.RealCount;
                model.Equity = trade.RealEquity;
                model.GEquity = found.GrEquity;
                model.Profit = (syl * trade.RealCount * trade.RealEquity);
                model.GProfit = (gssyl * trade.RealCount * trade.RealEquity);
                model.Id = trade.Id;
                model.Fee = trade.Fee;

                //Console.ForegroundColor = ConsoleColor.White;
                //Console.Write("{0}\t份{1,10}\t净{2,4:C}({3,4:C})", trade.FdCode, Math.Round(trade.RealCount, 2), Math.Round(trade.RealEquity, 2), found.GrEquity);

                //Console.Write("\t收");
                //Console.ForegroundColor = syl > 0 ? ConsoleColor.Red : ConsoleColor.Green;
                //Console.Write("{0,10:C}", syl * trade.RealCount * trade.RealEquity);
                //Console.ForegroundColor = ConsoleColor.White;

                //Console.Write("\t率");
                //Console.ForegroundColor = syl > 0 ? ConsoleColor.Red : ConsoleColor.Green;
                //Console.Write("{0,10:P}", syl);
                //Console.ForegroundColor = ConsoleColor.White;

                //Console.Write("\t估");
                //Console.ForegroundColor = gssyl > 0 ? ConsoleColor.Red : ConsoleColor.Green;
                //Console.Write("{0,10:C}", gssyl * trade.RealCount * trade.RealEquity);
                //Console.ForegroundColor = ConsoleColor.White;

                //Console.Write("\t率");

                //Console.ForegroundColor = gssyl > 0 ? ConsoleColor.Red : ConsoleColor.Green;

                //Console.Write("{0,10:P}", gssyl);
                //Console.ForegroundColor = ConsoleColor.White;
                //Console.Write(Environment.NewLine);

                //Console.WriteLine("{0}\t数量{2}\t成本{4:C}\t收益率{1:P}\t估算收益率{5:P}\t收益{3:C}", trade.FdCode, (found.Equity - trade.RealEquity) / found.Equity, trade.RealCount, (found.Equity - trade.RealEquity) / found.Equity*(trade.Principal- (trade.FeeType==0? trade.Fee:0)),
                //    trade.RealCount*trade.RealEquity+trade.Fee,
                //    found.GrEquity>0?(found.GrEquity - trade.RealEquity) / found.GrEquity:0);
            });
            //Console.WriteLine("".PadLeft(Console.BufferWidth, '-'));
            //trades.GroupBy(x => x.FdCode).ToList().ForEach(x => Console.WriteLine("{0}\t份{1,10}\t本{2,10:C}", x.Key, Math.Round(x.Sum(y => y.RealCount), 2), Math.Round(x.Sum(y => y.RealEquity * y.RealCount), 2)));
            //Console.WriteLine("".PadLeft(Console.BufferWidth, '-'));
            //Console.WriteLine("{0}\t份{1,10}\t本{2,10:C}\t估{3,10:C}", "合计", Math.Round(trades.Sum(y => y.RealCount), 2), Math.Round(trades.Sum(y => y.RealEquity * y.RealCount), 2), Math.Round(trades.Sum(y => y.RealCount * founds.First(f => f.Code == y.FdCode).GrEquity), 2));

            return rowModels;
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void btnAddFound_Click(object sender, EventArgs e)
        {
            AddFoundForm addFound=new AddFoundForm();
            addFound.Show();
        }

        private void btnShenGou_Click(object sender, EventArgs e)
        {
            BuyFoundForm buyFoundForm=new BuyFoundForm();
            buyFoundForm.Show();
        }
    }
}
